#!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask.ext.wtf import Form
from wtforms import StringField, TextField, BooleanField, SelectField, \
    SubmitField, IntegerField, SelectMultipleField, HiddenField
from wtforms.validators import Required, Length, Email, Regexp, IPAddress, NumberRange, \
    URL
# from wtforms_components  import read_only
from ..models import Tomcat, Project, Nginx, Host, Vhost
import os
from flask import current_app

from ..exceptions import ValidationError


class TomcatForm(Form):
    app_name = StringField('tomcat Name', validators=[
                           Required(), Length(1, 20)])
    app_cmd_start = StringField('tomcat start script', validators=[Required()])
    app_cmd_stop = StringField('tomcat stop script', validators=[Required()])
    app_comments = StringField('comments')

    http_port = IntegerField('http_port', validators=[
                             Required(), NumberRange(min=8000, max=9000)])
    ajp_port = IntegerField('ajp_port', validators=[
                            Required(), NumberRange(min=7000, max=7999)])
    host = SelectField('Host', coerce=int)
    submit = SubmitField('Submit')

    def __init__(self, *args, **kwargs):
        super(TomcatForm, self).__init__(*args, **kwargs)
        self.host.choices = [(host.id, host.hostname)
                             for host in Host.query.order_by(Host.hostname).all()]

    def validate_http_port(self, field):
        if Tomcat.query.filter_by(host_id=self.host.data).filter_by(_httpport=field.data).first():
            raise ValidationError(
                'The http port %s already used!' % field.data)
        # if field.data in  Tomcat.query.filter_by(_httpport=field.data).first():
        #     raise ValidationError('The http port %s already used!'%field.data)

    def validate_ajp_port(self, field):
        if Tomcat.query.filter_by(host_id=self.host.data).filter_by(_ajpport=field.data).first():
            raise ValidationError('The ajp port %s already used!' % field.data)
        # if field.data in  Tomcat.query.filter_by(_ajpport=field.data).first():
        #     raise ValidationError('The ajp port %s already used!'%field.data)

    def validate_app_name(self, field):
        if os.path.exists(current_app.config['TOMCAT_APPDIR'] + "/tomcat_" + field.data):
            raise ValidationError(
                "The Tomcat is exist at the /usr/local/%s" % field.data)


class EditTomcatForm(Form):
    app_id = HiddenField()
    app_name = StringField('tomcat Name', validators=[
                           Required(), Length(1, 20)])
    app_cmd_start = StringField('tomcat start script', validators=[Required()])
    app_cmd_stop = StringField('tomcat stop script', validators=[Required()])
    app_comments = StringField('comments')

    http_port = IntegerField('http_port', validators=[
                             Required(), NumberRange(min=8000, max=9000)])
    ajp_port = IntegerField('ajp_port', validators=[
                            Required(), NumberRange(min=7000, max=7999)])
    host = SelectField('Host', coerce=int)
    submit = SubmitField('Submit')

    def __init__(self, *args, **kwargs):
        super(EditTomcatForm, self).__init__(*args, **kwargs)
        self.host.choices = [(host.id, host.hostname)
                             for host in Host.query.order_by(Host.hostname).all()]

    def validate_http_port(self, field):
        tomcats = Tomcat.query.filter_by(
            host_id=self.host.data).filter_by(_httpport=field.data).first()
        if tomcats:
            if tomcats.id != int(self.app_id.data):
                raise ValidationError(
                    'The http port %s already used!' % field.data)

        # if field.data in  Tomcat.query.filter_by(_httpport=field.data).first():
        #     raise ValidationError('The http port %s already used!'%field.data)

    def validate_ajp_port(self, field):
        tomcats = Tomcat.query.filter_by(
            host_id=self.host.data).filter_by(_ajpport=field.data).first()
        if tomcats:
            if tomcats.id != int(self.app_id.data):
                raise ValidationError(
                    'The ajp port %s already used!' % field.data)

        # if field.data in  Tomcat.query.filter_by(_ajpport=field.data).first():
        #     raise ValidationError('The ajp port %s already used!'%field.data)
    def validate_host(self, field):
        host_id = Tomcat.query.get(int(self.app_id.data)).host.id
        print host_id, self.host.data
        if host_id != self.host.data:
            raise ValidationError("You Can't switch the hosts")


class NginxForm(Form):
    app_name = StringField('Nginx Name', validators=[
                           Required(), Length(1, 20)])
    app_dir = StringField('Nginx Dir', default='/etc/nginx')
    app_cmd_start = StringField(
        'Nginx start script', default='/etc/init.d/nginx start')
    app_cmd_stop = StringField(
        'Nginx stop script', default='/etc/init.d/nginx stop')
    app_comments = StringField('comments')

    host = SelectField('Host', coerce=int)
    submit = SubmitField('Submit')

    def __init__(self, *args, **kwargs):
        super(NginxForm, self).__init__(*args, **kwargs)
        self.host.choices = [(host.id, host.hostname)
                             for host in Host.query.order_by(Host.hostname).all()]


class VhostForm(Form):
    conf_name = StringField('Nginx vhost conf file ', validators=[
                            Required(), Length(1, 20)])
    nginx = SelectField('Nginx', coerce=int)
    submit = SubmitField('Submit')

    def __init__(self, *args, **kwargs):
        super(VhostForm, self).__init__(*args, **kwargs)
        self.nginx.choices = [(nginx.id, nginx.app_name)
                              for nginx in Nginx.query.order_by(Nginx.app_name).all()]


class ProjectForm(Form):

    name = StringField('Project Name', validators=[Required(), Length(1, 20)])
    domain = StringField('project domain', validators=[Required(), URL()])

    tomcat = SelectMultipleField('Tomcat', coerce=int)
    nginx = SelectMultipleField('Nginx', coerce=int)

    scmUrl = StringField('scm Url', validators=[URL()])
    srcDir = StringField('Project Name', validators=[Required()])
    submit = SubmitField('Submit')

    def __init__(self, *args, **kwargs):
        super(ProjectForm, self).__init__(*args, **kwargs)
        self.tomcat.choices = [
            (tomcat.id, tomcat.app_name) for tomcat in Tomcat.query.order_by(Tomcat.app_name).all()
        ]

        self.nginx.choices = [
            (nginx.id, nginx.app_name) for nginx in Nginx.query.order_by(Nginx.app_name).all()
        ]
